/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * frmListaBancos.java
 *
 * Created on 23/07/2012, 11:58:17 PM
 */

package Bancos;

import Beans.BancoBean;
import Blogic.BancoBLogic;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Vector;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author orellana
 */
public class frmListaBancos extends javax.swing.JFrame {

    // Atributos de la clase
    private String col[]={"Nombre", "Descripcion", "idBanco"};
    public DefaultTableModel modelBancos=new DefaultTableModel(col,0);
    private String bancoSel="";

    frmAltadeBanco altaBanco=null;
    /** Creates new form frmListaBancos */
    public frmListaBancos() {
        initComponents();

        //Posicionamos el formulario
        this.setLocationRelativeTo(null);
        //Redimencionamos el formulario
        this.setResizable(false);
        //Definimos el cerrado
        this.setDefaultCloseOperation(HIDE_ON_CLOSE);

        getTablaListadoBanco();

        obtBancos();

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jToolBar1 = new javax.swing.JToolBar();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jButton5 = new javax.swing.JButton();
        jTabbedPane1 = new javax.swing.JTabbedPane();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(sistemapegasso.SistemaPegassoApp.class).getContext().getResourceMap(frmListaBancos.class);
        setTitle(resourceMap.getString("Form.title")); // NOI18N
        setName("Form"); // NOI18N

        jToolBar1.setFloatable(false);
        jToolBar1.setRollover(true);
        jToolBar1.setName("jtbBarra"); // NOI18N

        jButton1.setIcon(resourceMap.getIcon("jButton1.icon")); // NOI18N
        jButton1.setText(resourceMap.getString("jButton1.text")); // NOI18N
        jButton1.setToolTipText(resourceMap.getString("jButton1.toolTipText")); // NOI18N
        jButton1.setFocusable(false);
        jButton1.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton1.setName("jButton1"); // NOI18N
        jButton1.setRequestFocusEnabled(false);
        jButton1.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        jToolBar1.add(jButton1);

        jButton2.setIcon(resourceMap.getIcon("btnModificar.icon")); // NOI18N
        jButton2.setText(resourceMap.getString("btnModificar.text")); // NOI18N
        jButton2.setToolTipText(resourceMap.getString("btnModificar.toolTipText")); // NOI18N
        jButton2.setFocusable(false);
        jButton2.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton2.setName("btnModificar"); // NOI18N
        jButton2.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        jToolBar1.add(jButton2);

        jButton4.setIcon(resourceMap.getIcon("btnEliminar.icon")); // NOI18N
        jButton4.setText(resourceMap.getString("btnEliminar.text")); // NOI18N
        jButton4.setToolTipText(resourceMap.getString("btnEliminar.toolTipText")); // NOI18N
        jButton4.setFocusable(false);
        jButton4.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton4.setName("btnEliminar"); // NOI18N
        jButton4.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });
        jToolBar1.add(jButton4);

        jButton3.setIcon(resourceMap.getIcon("btnBuscar.icon")); // NOI18N
        jButton3.setText(resourceMap.getString("btnBuscar.text")); // NOI18N
        jButton3.setToolTipText(resourceMap.getString("btnBuscar.toolTipText")); // NOI18N
        jButton3.setFocusable(false);
        jButton3.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton3.setName("btnBuscar"); // NOI18N
        jButton3.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });
        jToolBar1.add(jButton3);

        jButton5.setIcon(resourceMap.getIcon("btnCerrar.icon")); // NOI18N
        jButton5.setText(resourceMap.getString("btnCerrar.text")); // NOI18N
        jButton5.setToolTipText(resourceMap.getString("btnCerrar.toolTipText")); // NOI18N
        jButton5.setFocusable(false);
        jButton5.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton5.setName("btnCerrar"); // NOI18N
        jButton5.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });
        jToolBar1.add(jButton5);

        jTabbedPane1.setName("jTabbedPane1"); // NOI18N

        jPanel1.setName("jPanel1"); // NOI18N

        jLabel1.setBackground(resourceMap.getColor("jLabel1.background")); // NOI18N
        jLabel1.setFont(resourceMap.getFont("jLabel1.font")); // NOI18N
        jLabel1.setForeground(resourceMap.getColor("jLabel1.foreground")); // NOI18N
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N
        jLabel1.setOpaque(true);

        jLabel2.setFont(resourceMap.getFont("jLabel2.font")); // NOI18N
        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        jTextField1.setFont(resourceMap.getFont("txtNombre.font")); // NOI18N
        jTextField1.setText(resourceMap.getString("txtNombre.text")); // NOI18N
        jTextField1.setName("txtNombre"); // NOI18N
        jTextField1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jTextField1KeyPressed(evt);
            }
        });

        jLabel3.setBackground(resourceMap.getColor("jLabel3.background")); // NOI18N
        jLabel3.setFont(resourceMap.getFont("jLabel3.font")); // NOI18N
        jLabel3.setForeground(resourceMap.getColor("jLabel3.foreground")); // NOI18N
        jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N
        jLabel3.setName("jLabel3"); // NOI18N
        jLabel3.setOpaque(true);

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        jTable1.setFont(resourceMap.getFont("tblListaBancos.font")); // NOI18N
        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null},
                {null, null},
                {null, null},
                {null, null}
            },
            new String [] {
                "Nombre", "Descripcion"
            }
        ));
        jTable1.setName("tblListaBancos"); // NOI18N
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable1MouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);
        jTable1.getColumnModel().getColumn(0).setHeaderValue(resourceMap.getString("tblListaBancos.columnModel.title0")); // NOI18N
        jTable1.getColumnModel().getColumn(1).setHeaderValue(resourceMap.getString("tblListaBancos.columnModel.title1")); // NOI18N

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 630, Short.MAX_VALUE)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 398, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(159, Short.MAX_VALUE))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 606, Short.MAX_VALUE)
                .addContainerGap())
            .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, 630, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 176, Short.MAX_VALUE)
                .addContainerGap())
        );

        jTabbedPane1.addTab(resourceMap.getString("jPanel1.TabConstraints.tabTitle"), jPanel1); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jToolBar1, javax.swing.GroupLayout.DEFAULT_SIZE, 662, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addGap(12, 12, 12)
                .addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 638, Short.MAX_VALUE)
                .addGap(12, 12, 12))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 330, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

     //Actualizamos la tabla
    // Obtiene las Categorias Registradas
    public void obtBancos() {
        // Variables Locales
        Vector datosBancos = new Vector();
        BancoBean sqlBean = new BancoBean();
        // Obtenemos cantidad de registros de la tabla
        int count = modelBancos.getRowCount();
        // Hacemos un cliclo for para hacer la comparación
        for (int r = 0; r < count; r++) {
            // Eliminamos los datos que contenga la tabla
            modelBancos.removeRow(0);
        }
        // Realizamos la consulta
        datosBancos = (new BancoBLogic()).getDatosBancos(sqlBean);
        // Validamos registros encontrados
        if (!datosBancos.isEmpty()) {
            // Vaciamos los datos en la tabla
            // Ciclo for
            for (int i = 0; i < datosBancos.size(); i++) {
                BancoBean detalleDatosBanco = new BancoBean();
                detalleDatosBanco = (BancoBean) datosBancos.elementAt(i);
                // Vaciamos los datos
                modelBancos.addRow(new Object[]{detalleDatosBanco.getNombreBanco(), detalleDatosBanco.getDescripcionBanco(), detalleDatosBanco.getIdBanco()});
            }
        } else {
            modelBancos.addRow(new Object[]{"No existen bancos registradas"});
        }
    }


    private void deleteRowModelTable(){
        // Limpiamos el Modelo de la Tabla
        while (modelBancos.getRowCount()>0){
            modelBancos.removeRow(0);
        }
    }


     // Obtiene tamaño columnas tablas
    public void getTablaListadoBanco(){
        // Vaciamos el modelo con los datos
        jTable1.setModel(modelBancos);
        // Definimos el tamaño de las columnas
        // Nombre Banco
        jTable1.getColumnModel().getColumn(0).setPreferredWidth(350);
        // Descripcion
        jTable1.getColumnModel().getColumn(1).setPreferredWidth(200);
        // IdBanco
        jTable1.getColumnModel().getColumn(2).setMinWidth(0);
        jTable1.getColumnModel().getColumn(2).setMaxWidth(0);
    }


    //Boton nuevo
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
   altaBanco=new frmAltadeBanco(1);
   altaBanco.jButton1.setActionCommand("nuevaAltaBanco");
   altaBanco.jButton1.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent ae) {
                if(ae.getActionCommand().equals("nuevaAltaBanco")){
                    altaBanco.altaClickBanco();
                    obtBancos();

                }
            }
        });
   altaBanco.setVisible(true);
    }//GEN-LAST:event_jButton1ActionPerformed

    //Eliminamos banco del listado de banco
    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        // TODO add your handling code here:
        //Asignamos variables locales
        BancoBean sqlBancoBean= new BancoBean();
        Vector eliminarBanco=new Vector();

        //Eliminamos la categoria seleccionada
        //Verificamos que se haya seleccionado un registro
        if(!bancoSel.equalsIgnoreCase("")){
            //Seteamos los datos

            sqlBancoBean.setIdBanco(modelBancos.getValueAt(Integer.parseInt(bancoSel.toString()),2).toString());
            //Eliminamos banco
            eliminarBanco = (new BancoBLogic()).deleteDatosBanco(sqlBancoBean);
            //Evaluamos respuesta
             if (eliminarBanco.elementAt(0).toString().equalsIgnoreCase("OK")){
          bancoSel="";
                // Mensaje al Usuario
                JOptionPane.showMessageDialog(null,"Banco Eliminado Satisfactoriamente","Eliminar",JOptionPane.INFORMATION_MESSAGE);
                obtBancos();
                System.out.println("entro aka");
                // Limpiamos Variable
                //obtCategorias();
                //categoriaSel="";

            }else{
                // Mensaje al Usuario
                JOptionPane.showMessageDialog(null,"Ocurrio un Error al Momento de Eliminar el Banco","Eliminar",JOptionPane.ERROR_MESSAGE);
            }
        }else{
            // Mensaje al Usuario
            JOptionPane.showMessageDialog(null,"Debe Seleccionar un Registro a Eliminar, Verifique","Eliminar",JOptionPane.ERROR_MESSAGE);
        }

    }//GEN-LAST:event_jButton4ActionPerformed

    private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked
        // TODO add your handling code here:
         this.bancoSel=Integer.toString(jTable1.getSelectedRow());
    }//GEN-LAST:event_jTable1MouseClicked

    //Modificamos banco
    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:

        // Evaluamos si selecciono alguna categoria a modificar
        if(!bancoSel.equalsIgnoreCase("")){
            System.out.println("Entre akiiii");
        //Cargamos el formulario modificar banco
        final frmAltadeBanco modificarBanco=new frmAltadeBanco(2);
        //Cambiamos titulo de la ventana
        modificarBanco.setTitle(".:: Modificar Banco ::.");
        // Seteamos los Datos
        modificarBanco.setIdBanco(modelBancos.getValueAt(Integer.parseInt(bancoSel.toString()),2).toString());
        //System.out.println("imprime"+ modelCategorias.getValueAt(Integer.parseInt(categoriaSel.toString()),2).toString());
        // Obtenemos los Datos del Cliente
        modificarBanco.obtDatosBanco();

        // Cambiamos el Valor del Cliente Seleccionado
        bancoSel="";
        //Mostramos la ventana modificar banco
        modificarBanco.setVisible(true);

        modificarBanco.jButton1.setActionCommand("nuevaAltaBanco");
        modificarBanco.jButton1.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
               if (e.getActionCommand().equals("nuevaAltaBanco")){
               modificarBanco.altaClickBanco();
               obtBancos();
               }
            }
        });

        }else{
        // Mensaje al usuario
            JOptionPane.showMessageDialog(null,"Debe Seleccionar un Banco a Modificar, Verifique...","Bancos",JOptionPane.WARNING_MESSAGE);
        }
    }//GEN-LAST:event_jButton2ActionPerformed

    //Buscar registros
    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        // TODO add your handling code here:

         // Variables locales
        BancoBean sqlBean=new BancoBean();
        Vector datosBancoActivos= new Vector();
        BancoBean bancoActivos= new BancoBean();
System.out.println("Entre akiiii buscar");
        //Realizamos la busqueda de la categoria
        //Seteamos los datos
        sqlBean.setNombreBanco(jTextField1.getText());
        datosBancoActivos=(new BancoBLogic().buscarDatosBancoActivo(sqlBean));
        //Limpiamos la tabla
        deleteRowModelTable();
        //Evaluamos resultado obtenido
        if(datosBancoActivos.size()!=0){
        //Agregamos los datos al modelo
            for(int i=0; i<datosBancoActivos.size();i++){
                //Vaciamos los datos
                //CategoriaBean categoriaActivos = new CategoriaBean();
            bancoActivos=(BancoBean) datosBancoActivos.elementAt(i);
            //Agregamos los datos al modelo de la tabla
            modelBancos.addRow(new Object[]{bancoActivos.getNombreBanco(),bancoActivos.getDescripcionBanco(),bancoActivos.getIdBanco()});
       // System.out.println("imprime categorias "+modelCategorias);
            }
        }else{
        //No existen registros
            //modelCategorias.addRow(new Object[]{"No existen categorias registradas"});

        }

    }//GEN-LAST:event_jButton3ActionPerformed

    //Buscamos bancos al ingresar caracteres en la caja de texto
    private void jTextField1KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField1KeyPressed
        // TODO add your handling code here:

         System.out.println("entre akii");
        BancoBean buscarBanco = new BancoBean();
        Vector bancoVector = new Vector();
        BancoBLogic bancoBlogic= new BancoBLogic();
        buscarBanco.setNombreBanco(jTextField1.getText().toString().trim());

        bancoVector=bancoBlogic.buscarDatosBancoActivo(buscarBanco);
        if(bancoVector.size()>0){
           deleteRowModelTable();
           for(int i=0; i<bancoVector.size();i++){
               buscarBanco=(BancoBean) bancoVector.elementAt(i);
           modelBancos.addRow(new Object[]{buscarBanco.getNombreBanco(), buscarBanco.getDescripcionBanco(),buscarBanco.getIdBanco()});
        }
        }
    }//GEN-LAST:event_jTextField1KeyPressed

    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
        // TODO add your handling code here:

        this.setVisible(false);
    }//GEN-LAST:event_jButton5ActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new frmListaBancos().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JToolBar jToolBar1;
    // End of variables declaration//GEN-END:variables

}
